/** Axios请求
 * @Author: xuhong
 * @Date: 2020/6/19
 * @DESC: //TODO
 */
import axios from 'axios';
import { Message } from 'element-ui'


axios.defaults.withCredentials = true; // 设置跨域请求提供凭据信息
//创建axios实例
const service = axios.create({
  baseURL: "",
  timeout: 5000
});
//请求拦截器
service.interceptors.request.use(
  config => {
    //请求发送之前做一些处理
    // if (!(config.headers['Content-Type'])) {
    //   
    //   if (config.method == 'post') {
    //     config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    //     for (var key in config.data) {
    //       if (config.data[key] === '') {
    //         delete config.data[key]
    //       }
    //     }
    //     config.data = JSON.stringify(config.data)
    //   } else {
    //     config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    //     config.data = JSON.stringify(config.data)
    //   }
    // }
    // const token = "token";
    // // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    // if (token) {
    //   config.headers['Authorization'] = token;
    // }
    return config;
  },
  error => {
    Message.error(error);
    // 发送失败
    console.log(error);
    return Promise.reject(error);
  }
);
//响应拦截器
service.interceptors.response.use(
  response => {
    // dataAxios 是 axios 返回数据中的 data
    // loadingInstance.close();
    const dataAxios = response.data;
    return dataAxios;
  },
  error => {
    return Promise.reject(error);
  }
);
// 封装get
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params
      })
      .then(
        res => {
          resolve(res.data);
        },
        err => {
          Message.error({message: '获取数据失败'});
        }
      )
      .catch(err => {
        Message.error(err.message);
        reject(err);
      });
  });
}
//封装post请求
export function post(url, data = {}) {
  //默认配置
  let sendObject = {
    url: url,
    method: "post",
    headers: {
      "Content-Type": "application/json;charset=UTF-8"
    },
    data: data
  };
  sendObject.data = JSON.stringify(data);
  return service(sendObject);
}

export default {
  service,
  get,
  post
};